/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.android.os;

import android.os.Handler;
import java.util.List;
import java.util.ArrayList;
import android.util.Log;

public class Subject {
    private static final String TAG = "Subject";
    private List<EventObserver> mObservers = new ArrayList<>();

    public synchronized void registerObserver(EventObserver observer) {
        removeCleared();
        mObservers.add(observer);
    }

    public synchronized void unregisterObserver(EventObserver observer) {
        remove(observer.getHandler());
    }

    public synchronized void removeCleared() {
        for (int i = mObservers.size() - 1; i >= 0 ; i--) {
            EventObserver  r = (EventObserver) mObservers.get(i);
            if (r.refH == null) {
                mObservers.remove(i);
            }
        }
    }

    public synchronized void remove(Handler h) {
        for (int i = 0, s = mObservers.size() ; i < s ; i++) {
            EventObserver  o = (EventObserver) mObservers.get(i);
            Handler     rh;

            rh = o.getHandler();

            /* Clean up both the requested registrant and
             * any now-collected registrants
             */
            if (rh == null || rh == h) {
                o.clear();
            }
        }

        removeCleared();
    }

    public synchronized void notifyObservers(MessageData data) {
        int count = mObservers.size();
        for (int i=0; i<count; i++) {
            EventObserver  r = (EventObserver) mObservers.get(i);
            r.notify(data);
            if (i != count-1) {
                try {
                    data = data.clone();
                    data.markUnuse();
                } catch (CloneNotSupportedException e) {
                    Log.e(TAG, "clone MessageData failed " + e);
                }
            }
        }

    }
}

